import 'dart:convert';
import 'dart:io';
import 'dart:ui';

import 'package:douhuaxiangsu/page/sketchpad.dart';
import 'package:douhuaxiangsu/page/setting.dart';
import 'package:douhuaxiangsu/services/artwork_service.dart';
import 'package:douhuaxiangsu/services/global_config_service.dart';
import 'package:douhuaxiangsu/utils/db_utils.dart';
import 'package:douhuaxiangsu/widgets/toast.dart';
import 'package:flutter/material.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';

import 'entity/artwork_model.dart';

void main() async {
  if (Platform.isWindows || Platform.isLinux) {
    // 对于桌面平台，需要显式初始化
    sqfliteFfiInit();
    databaseFactory = databaseFactoryFfi;
  }
  await DbUtils.initDatabase();
  runApp(MyApp());
  // 启用边界绘制调试
  // debugPaintSizeEnabled = true;

  // 显示基线
  // debugPaintBaselinesEnabled = true;

  // 显示指针事件边界
  // debugPaintPointersEnabled = true;
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: HomePage());
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<ArtworkModel> artworkList = [];

  @override
  void initState() {
    super.initState();
    _loadArtworks();
  }

  Future<void> _loadArtworks() async {
    final artworks = await ArtworkService.queryAll();
    setState(() {
      artworkList = artworks;
    });
  }

  @override
  Widget build(BuildContext context) {
    MediaQueryData mediaQuery = MediaQuery.of(context);
    // 包含安全区域的尺寸
    double safeWidth = mediaQuery.size.width;
    double itemWidthMin = 180;
    var columnCount = safeWidth < itemWidthMin
        ? 1
        : (safeWidth / itemWidthMin).floor();
    var itemWidth = safeWidth / columnCount - 20;

    return Scaffold(
      appBar: AppBar(
        title: const Text('豆画像素'),
        // 右上角按钮区域
        actions: [
          IconButton(
            icon: const Icon(Icons.menu),
            tooltip: '设置',
            onPressed: () {
              // 点击后跳转到设置页
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => const SettingsPage()),
              );
            },
          ),
        ],
      ),
      body: ScrollConfiguration(
        behavior: ScrollConfiguration.of(context).copyWith(
          dragDevices: {PointerDeviceKind.mouse, PointerDeviceKind.touch},
        ),
        child: GridView.count(
          crossAxisCount: columnCount,
          children: List.generate(artworkList.length, (index) {
            ArtworkModel artworkModel = artworkList[index];
            return GestureDetector(
              child: Column(
                children: [
                  artworkModel.image64 == null
                      ? Image.asset(
                          'images/hide_image_256dp_1F1F1F.png',
                          width: itemWidth,
                          height: itemWidth,
                        )
                      : Image.memory(
                          base64Decode(artworkModel.image64!),
                          fit: BoxFit.cover,
                          width: itemWidth,
                          height: itemWidth,
                        ),
                  Text(
                    artworkModel.canvas.size.toJson().toString(),
                    style: TextStyle(fontSize: 12.0, color: Colors.grey[800]),
                  ),
                ],
              ),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) =>
                        SketchpadPage(artworkModel: artworkModel),
                  ),
                ).then((value) {
                  _loadArtworks();
                });
              },
              onLongPress: () {
                _showArtworkContextMenu(context, artworkModel);
              },
              onSecondaryTap: () {
                _showArtworkContextMenu(context, artworkModel);
              },
            );
          }),
        ),
      ),
      bottomNavigationBar: BottomAppBar(
        shape: const CircularNotchedRectangle(),
        child: Container(height: 50.0),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _showCenterPopup(context),
        tooltip: '新建作品',
        child: const Icon(Icons.add),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
    );
  }

  /// 显示中间弹窗
  void _showCenterPopup(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('新建作品'),
          // 弹窗内容区域
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 选项列表
                ListTile(
                  title: Text('导入图片'),
                  onTap: () {
                    Toast.show('此功能还未实现', context);
                  },
                ),
                ListTile(
                  title: Text('导入源文件(.dhxs)'),
                  onTap: () {
                    Toast.show('此功能还未实现', context);
                  },
                ),
                _buildOption('8×8', 8, null, context),
                _buildOption('16×16', 16, null, context),
                _buildOption('32×32', 32, null, context),
                _buildOption('64×64', 64, null, context),
                _buildOption('128×128', 128, null, context),
                _buildOption('256×256', 256, null, context),
                ListTile(
                  title: Text('自定义画布'),
                  onTap: () {
                    showDialog(
                      context: context,
                      builder: (BuildContext context) {
                        TextEditingController widthController =
                            TextEditingController();
                        TextEditingController heightController =
                            TextEditingController();

                        return AlertDialog(
                          title: const Text('修改画布大小'),
                          content: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Row(
                                children: [
                                  Expanded(
                                    child: TextField(
                                      controller: widthController,
                                      decoration: const InputDecoration(
                                        labelText: '宽度',
                                        border: OutlineInputBorder(),
                                      ),
                                      keyboardType: TextInputType.number,
                                    ),
                                  ),
                                  const SizedBox(width: 8),
                                  const Text('x'),
                                  const SizedBox(width: 8),
                                  Expanded(
                                    child: TextField(
                                      controller: heightController,
                                      decoration: const InputDecoration(
                                        labelText: '高度',
                                        border: OutlineInputBorder(),
                                      ),
                                      keyboardType: TextInputType.number,
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                          actions: [
                            TextButton(
                              onPressed: () => Navigator.of(context).pop(),
                              child: const Text('取消'),
                            ),
                            TextButton(
                              onPressed: () {
                                int? xPos = int.tryParse(widthController.text),
                                    yPos = int.tryParse(heightController.text);
                                if (xPos == null ||
                                    yPos == null ||
                                    xPos < 1 ||
                                    yPos < 1) {
                                  Toast.show('请输入有效的数字', context);
                                  return;
                                }
                                if (xPos > 256 || yPos > 256) {
                                  Toast.show('画布最大尺寸为256*256', context);
                                  return;
                                }
                                //这里pop两遍是对的,关掉两个弹窗
                                Navigator.of(context).pop();
                                Navigator.of(context).pop();
                                _createSquareNew(xPos, yPos, context);
                              },
                              child: const Text('确定'),
                            ),
                          ],
                        );
                      },
                    );
                  },
                ),
                ListTile(
                  title: Text('圆形画布'),
                  onTap: () {
                    Toast.show('此功能还未实现', context);
                  },
                ),
                ListTile(
                  title: Text('正六边形画布'),
                  onTap: () {
                    Toast.show('此功能还未实现', context);
                  },
                ),
              ],
            ),
          ),
          // 底部按钮
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('关闭'),
            ),
          ],
        );
      },
    );
  }

  /// 显示作品上下文菜单
  void _showArtworkContextMenu(
    BuildContext context,
    ArtworkModel artworkModel,
  ) {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext buildContext) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              _buildContextMenuItem('导出图片(PNG)', Icons.image, () {
                Navigator.pop(buildContext);
                // TODO: 实现导出图片功能
                if (!mounted) return;
                Toast.show('导出图片功能待实现', context);
              }),
              _buildContextMenuItem('导出源文件', Icons.file_download, () {
                Navigator.pop(buildContext);
                // TODO: 实现导出源文件功能
                if (!mounted) return;
                Toast.show('导出源文件功能待实现', context);
              }),
              _buildContextMenuItem('复制', Icons.copy, () {
                Navigator.pop(buildContext);
                if (!mounted) return;
                ArtworkService.insert(artworkModel);
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) =>
                        SketchpadPage(artworkModel: artworkModel),
                  ),
                );
              }),
              _buildContextMenuItem('删除', Icons.delete, () {
                Navigator.pop(buildContext);
                _deleteArtwork(artworkModel);
              }),
            ],
          ),
        );
      },
    );
  }

  /// 构建上下文菜单项
  Widget _buildContextMenuItem(
    String title,
    IconData icon,
    VoidCallback onTap,
  ) {
    return ListTile(leading: Icon(icon), title: Text(title), onTap: onTap);
  }

  /// 删除作品（带二次确认）
  Future<void> _deleteArtwork(ArtworkModel artworkModel) async {
    return showDialog<void>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext dialogContext) {
        return AlertDialog(
          title: const Text('确认删除'),
          content: Text(
            '确定要删除作品 "${artworkModel.canvas.size.toJson()}" 吗？此操作无法撤销。',
          ),
          actions: <Widget>[
            TextButton(
              child: const Text('取消'),
              onPressed: () {
                Navigator.of(dialogContext).pop();
              },
            ),
            ElevatedButton(
              child: const Text('删除'),
              onPressed: () async {
                Navigator.of(dialogContext).pop();
                // 执行删除操作
                await ArtworkService.delete(artworkModel.id!);
                // 检查 mounted 状态
                if (!mounted) return;
                if (!context.mounted) return;
                Toast.show('作品已删除', context);
                // 重新加载作品列表
                _loadArtworks();
              },
            ),
          ],
        );
      },
    );
  }

  /// 构建选项组件
  Widget _buildOption(
    String text,
    int sizeX,
    int? sizeY,
    BuildContext context,
  ) {
    return ListTile(
      title: Text(text),
      onTap: () {
        // 关闭弹窗
        Navigator.of(context).pop();
        _createSquareNew(sizeX, sizeY, context);
      },
    );
  }

  /// 创建新正方形画布
  void _createSquareNew(int sizeX, int? sizeY, BuildContext context) {
    ArtworkModel artworkModel = ArtworkModel.fromJson(
      jsonDecode(
        '{"canvas":{"type":0,"size":{"x":32,"y":32},"pointStyle":{"type":"default","data":"1"}}}',
      ),
    );
    artworkModel.canvas.size = SizeModel(x: sizeX, y: sizeY ?? sizeX);
    GlobalConfigService.getCanvasConfig().then((gs) {
      artworkModel.canvas.canvasConfig = gs;
      ArtworkService.insert(artworkModel);
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => SketchpadPage(artworkModel: artworkModel),
        ),
      ).then((result) {
        _loadArtworks();
      });
    });
  }
}
